<template>
  <div class="transport-plan-detail-container">
    <div class="page-header">
      <div class="header-title">
        <h2>运输计划详情</h2>
        <span class="subtitle">查看运输计划详细信息</span>
      </div>
      <div class="header-actions">
        <el-button @click="goBack">
          <el-icon><Back /></el-icon>返回列表
        </el-button>
        <el-button type="primary" @click="handlePrint">
          <el-icon><Printer /></el-icon>打印计划
        </el-button>
        <el-button type="success" v-if="plan.status === 'planning'" @click="handleStartExecution">
          <el-icon><VideoPlay /></el-icon>开始执行
        </el-button>
      </div>
    </div>

    <el-card v-loading="loading">
      <!-- 计划状态 -->
      <div class="plan-status">
        <div class="status-tag">
          <el-tag :type="getStatusType(plan.status)" size="large">
            {{ getStatusLabel(plan.status) }}
          </el-tag>
        </div>
        <el-steps :active="getStatusStep(plan.status)" finish-status="success" simple>
          <el-step title="计划中" />
          <el-step title="执行中" />
          <el-step title="已完成" />
        </el-steps>
      </div>

      <!-- 计划基本信息 -->
      <el-descriptions title="计划信息" :column="3" border>
        <el-descriptions-item label="计划编号">{{ plan.planNo }}</el-descriptions-item>
        <el-descriptions-item label="计划名称">{{ plan.planName }}</el-descriptions-item>
        <el-descriptions-item label="计划日期">{{ plan.planDate }}</el-descriptions-item>
        <el-descriptions-item label="计划人">{{ plan.planner }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ plan.createTime }}</el-descriptions-item>
        <el-descriptions-item label="最后更新时间">{{ plan.updateTime }}</el-descriptions-item>
        <el-descriptions-item label="计划描述" :span="3">{{ plan.description }}</el-descriptions-item>
      </el-descriptions>

      <!-- 统计信息 -->
      <div class="statistics-container">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="statistic-card">
              <div class="statistic-value">{{ plan.orderCount }}</div>
              <div class="statistic-label">订单数量</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="statistic-card">
              <div class="statistic-value">{{ plan.vehicleCount }}</div>
              <div class="statistic-label">车辆数量</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="statistic-card">
              <div class="statistic-value">{{ plan.totalDistance }} km</div>
              <div class="statistic-label">总里程</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="statistic-card">
              <div class="statistic-value">¥ {{ plan.totalCost.toFixed(2) }}</div>
              <div class="statistic-label">总成本</div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 订单信息 -->
      <div class="section-title">订单列表</div>
      <el-table :data="plan.orders" border style="width: 100%">
        <el-table-column prop="orderNo" label="订单号" width="150"></el-table-column>
        <el-table-column prop="customer" label="客户名称" min-width="150"></el-table-column>
        <el-table-column prop="fromAddress" label="起始地" min-width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="toAddress" label="目的地" min-width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="expectedPickupTime" label="预计提货时间" width="180"></el-table-column>
        <el-table-column prop="expectedDeliveryTime" label="预计送达时间" width="180"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getOrderStatusType(scope.row.status)">
              {{ getOrderStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewOrderDetail(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 车辆分配 -->
      <div class="section-title">车辆分配</div>
      <el-table :data="plan.vehicleAssignments" border style="width: 100%">
        <el-table-column prop="vehicle.plateNumber" label="车牌号" width="120"></el-table-column>
        <el-table-column prop="vehicle.type" label="车辆类型" width="120"></el-table-column>
        <el-table-column prop="driver.name" label="驾驶员" width="100"></el-table-column>
        <el-table-column prop="driver.phone" label="联系电话" width="130"></el-table-column>
        <el-table-column prop="assignedOrders" label="分配订单" min-width="200">
          <template #default="scope">
            <el-tag 
              v-for="order in scope.row.assignedOrders" 
              :key="order.id"
              size="small"
              class="order-tag"
            >
              {{ order.orderNo }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180"></el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getVehicleAssignmentStatusType(scope.row.status)">
              {{ getVehicleAssignmentStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button 
              size="small" 
              @click="viewVehicleRoute(scope.row)"
              :disabled="scope.row.status === 'pending'"
            >
              查看路线
            </el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="editVehicleAssignment(scope.row)"
              :disabled="['completed', 'cancelled'].includes(plan.status)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 路线地图 -->
      <div class="section-title">路线地图</div>
      <div class="map-container">
        <div class="map-placeholder">
          <el-empty description="地图加载中...">
            <template #image>
              <el-icon style="font-size: 60px"><Location /></el-icon>
            </template>
            <template #description>
              <p>此处将显示运输计划的路线图</p>
            </template>
          </el-empty>
        </div>
      </div>

      <!-- 执行记录 -->
      <div v-if="['executing', 'completed'].includes(plan.status)" class="section-title">执行记录</div>
      <div v-if="['executing', 'completed'].includes(plan.status)" class="execution-timeline">
        <el-timeline>
          <el-timeline-item
            v-for="(record, index) in plan.executionRecords"
            :key="index"
            :timestamp="record.time"
            :type="getExecutionRecordType(record.type)"
          >
            {{ record.description }}
            <div v-if="record.operator" class="record-operator">操作人: {{ record.operator }}</div>
          </el-timeline-item>
        </el-timeline>
      </div>

      <!-- 操作记录 -->
      <div class="section-title">操作记录</div>
      <el-table :data="plan.operationLogs" border style="width: 100%">
        <el-table-column prop="time" label="操作时间" width="180"></el-table-column>
        <el-table-column prop="operator" label="操作人" width="120"></el-table-column>
        <el-table-column prop="action" label="操作类型" width="120">
          <template #default="scope">
            <el-tag>{{ scope.row.action }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="操作描述" min-width="200"></el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150"></el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Back, Printer, VideoPlay, Location } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

// 加载状态
const loading = ref(true)

// 计划数据
const plan = ref({
  id: 1,
  planNo: 'TP-2025031501',
  planName: '北京-上海运输计划',
  planDate: '2025-03-15',
  planner: '张经理',
  createTime: '2025-03-14 15:30:22',
  updateTime: '2025-03-14 16:45:10',
  description: '这是一个从北京到上海的运输计划，包含多个客户的订单，需要协调多辆车辆进行运输。',
  status: 'planning',
  orderCount: 5,
  vehicleCount: 3,
  totalDistance: 1200,
  totalCost: 15000.00,
  orders: [
    {
      id: 1,
      orderNo: 'TMS-2025031401',
      customer: '北京物流科技有限公司',
      fromAddress: '北京市朝阳区建国路88号',
      toAddress: '上海市浦东新区张江高科技园区',
      expectedPickupTime: '2025-03-15 09:00:00',
      expectedDeliveryTime: '2025-03-16 18:00:00',
      status: 'confirmed'
    },
    {
      id: 2,
      orderNo: 'TMS-2025031402',
      customer: '上海贸易有限公司',
      fromAddress: '北京市海淀区中关村大街1号',
      toAddress: '上海市黄浦区南京东路1号',
      expectedPickupTime: '2025-03-15 10:00:00',
      expectedDeliveryTime: '2025-03-16 19:00:00',
      status: 'confirmed'
    },
    {
      id: 3,
      orderNo: 'TMS-2025031403',
      customer: '北京电子设备有限公司',
      fromAddress: '北京市丰台区丰台科技园',
      toAddress: '上海市静安区南京西路1788号',
      expectedPickupTime: '2025-03-15 11:00:00',
      expectedDeliveryTime: '2025-03-16 20:00:00',
      status: 'confirmed'
    },
    {
      id: 4,
      orderNo: 'TMS-2025031404',
      customer: '北京科技发展有限公司',
      fromAddress: '北京市昌平区回龙观东大街',
      toAddress: '上海市徐汇区虹桥路1号',
      expectedPickupTime: '2025-03-15 13:00:00',
      expectedDeliveryTime: '2025-03-16 21:00:00',
      status: 'confirmed'
    },
    {
      id: 5,
      orderNo: 'TMS-2025031405',
      customer: '北京网络科技有限公司',
      fromAddress: '北京市东城区东直门外大街',
      toAddress: '上海市长宁区中山公园',
      expectedPickupTime: '2025-03-15 14:00:00',
      expectedDeliveryTime: '2025-03-16 22:00:00',
      status: 'confirmed'
    }
  ],
  vehicleAssignments: [
    {
      id: 1,
      vehicle: {
        id: 1,
        plateNumber: '京A12345',
        type: '中型厢式货车'
      },
      driver: {
        id: 1,
        name: '王师傅',
        phone: '13811112222'
      },
      assignedOrders: [
        { id: 1, orderNo: 'TMS-2025031401' },
        { id: 2, orderNo: 'TMS-2025031402' }
      ],
      startTime: '2025-03-15 09:00:00',
      endTime: '2025-03-16 18:00:00',
      status: 'pending'
    },
    {
      id: 2,
      vehicle: {
        id: 2,
        plateNumber: '京B67890',
        type: '大型厢式货车'
      },
      driver: {
        id: 2,
        name: '李师傅',
        phone: '13833334444'
      },
      assignedOrders: [
        { id: 3, orderNo: 'TMS-2025031403' }
      ],
      startTime: '2025-03-15 11:00:00',
      endTime: '2025-03-16 20:00:00',
      status: 'pending'
    },
    {
      id: 3,
      vehicle: {
        id: 3,
        plateNumber: '京C13579',
        type: '中型厢式货车'
      },
      driver: {
        id: 3,
        name: '赵师傅',
        phone: '13855556666'
      },
      assignedOrders: [
        { id: 4, orderNo: 'TMS-2025031404' },
        { id: 5, orderNo: 'TMS-2025031405' }
      ],
      startTime: '2025-03-15 13:00:00',
      endTime: '2025-03-16 22:00:00',
      status: 'pending'
    }
  ],
  executionRecords: [],
  operationLogs: [
    {
      time: '2025-03-14 15:30:22',
      operator: '张经理',
      action: '创建',
      description: '创建运输计划',
      remark: ''
    },
    {
      time: '2025-03-14 16:45:10',
      operator: '张经理',
      action: '编辑',
      description: '更新车辆分配信息',
      remark: '调整了车辆和订单的匹配'
    }
  ]
})

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'planning': 'info',
    'executing': 'warning',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态标签
const getStatusLabel = (status) => {
  const statusMap = {
    'planning': '计划中',
    'executing': '执行中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || '未知'
}

// 获取状态步骤
const getStatusStep = (status) => {
  const statusStepMap = {
    'planning': 0,
    'executing': 1,
    'completed': 2,
    'cancelled': 0
  }
  return statusStepMap[status] || 0
}

// 获取订单状态类型
const getOrderStatusType = (status) => {
  const statusMap = {
    'pending': 'info',
    'confirmed': 'primary',
    'assigned': 'warning',
    'intransit': 'success',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取订单状态标签
const getOrderStatusLabel = (status) => {
  const statusMap = {
    'pending': '待审核',
    'confirmed': '已确认',
    'assigned': '已分配',
    'intransit': '运输中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || '未知'
}

// 获取车辆分配状态类型
const getVehicleAssignmentStatusType = (status) => {
  const statusMap = {
    'pending': 'info',
    'inprogress': 'warning',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取车辆分配状态标签
const getVehicleAssignmentStatusLabel = (status) => {
  const statusMap = {
    'pending': '待执行',
    'inprogress': '进行中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || '未知'
}

// 获取执行记录类型
const getExecutionRecordType = (type) => {
  const typeMap = {
    'start': 'primary',
    'pickup': 'success',
    'delivery': 'success',
    'complete': 'success',
    'exception': 'danger'
  }
  return typeMap[type] || 'info'
}

// 返回列表
const goBack = () => {
  router.push('/transport/plan')
}

// 打印计划
const handlePrint = () => {
  window.print()
}

// 开始执行
const handleStartExecution = () => {
  ElMessageBox.confirm(
    `确定要开始执行运输计划 "${plan.value.planName}" 吗？`,
    '确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际应用中应该调用API更新计划状态
    plan.value.status = 'executing'
    
    // 更新车辆分配状态
    plan.value.vehicleAssignments.forEach(assignment => {
      assignment.status = 'inprogress'
    })
    
    // 添加执行记录
    plan.value.executionRecords.push({
      time: new Date().toLocaleString(),
      type: 'start',
      description: '开始执行运输计划',
      operator: '当前用户'
    })
    
    // 添加操作记录
    plan.value.operationLogs.push({
      time: new Date().toLocaleString(),
      operator: '当前用户',
      action: '执行',
      description: '开始执行运输计划',
      remark: ''
    })
    
    ElMessage.success('计划已开始执行')
  }).catch(() => {
    // 取消操作
  })
}

// 查看订单详情
const viewOrderDetail = (order) => {
  router.push(`/order/detail/${order.id}`)
}

// 查看车辆路线
const viewVehicleRoute = (assignment) => {
  // 实际应用中应该跳转到路线详情页或显示路线弹窗
  ElMessage.info(`查看车辆 ${assignment.vehicle.plateNumber} 的路线`)
}

// 编辑车辆分配
const editVehicleAssignment = (assignment) => {
  // 实际应用中应该跳转到编辑页面或显示编辑弹窗
  ElMessage.info(`编辑车辆 ${assignment.vehicle.plateNumber} 的分配信息`)
}

onMounted(() => {
  // 获取计划ID
  const planId = route.params.id
  
  // 实际应用中应该调用API获取计划详情
  setTimeout(() => {
    // 模拟API调用
    loading.value = false
  }, 500)
})
</script>

<style scoped>
.transport-plan-detail-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.plan-status {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.status-tag {
  margin-right: 30px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin: 30px 0 15px;
  color: #303133;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
}

.statistics-container {
  margin: 30px 0;
}

.statistic-card {
  text-align: center;
  padding: 20px;
}

.statistic-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 10px;
}

.statistic-label {
  font-size: 14px;
  color: #606266;
}

.order-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.map-container {
  height: 400px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.map-placeholder {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.execution-timeline {
  margin: 20px 0;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.record-operator {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

@media print {
  .header-actions {
    display: none;
  }
}
</style>
